<?php

namespace Beerus\Modules\Peanut\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\Peanut\Actions\EditBackStatus;
use Beerus\Modules\Peanut\Actions\TagManyStatus;
use Beerus\Modules\Peanut\Actions\UndoTransferRecord;
use Biz\model\taobao\TaoBaoUserAuth;
use Doctrine\DBAL\Exception;
use Doraemon\model\SellGoods\SellGoodsAccountInfo;
use Doraemon\model\SellGoods\SellGoodsBackOrder;
use Doraemon\model\SellGoods\SellGoodsTransferRecord;
use Doraemon\service\SellGoods\User;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Tools\BatchActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use function Clue\StreamFilter\fun;

class TransferController extends Controller
{
    /**
     * @Notes: 转账列表
     * @param Content $content
     * @param Request $request
     * @return Content
     * @author: weiyizheng
     * @Time: 2021/12/31
     */
    public function index(Content $content, Request $request)
    {
        $pageSize = $request->input('per_page', 10);
        $page = $request->input('page', 1);

        $condition = $this->getSearchWhere($request);

        $total = count(SellGoodsBackOrder::select(['id'], $condition));
        // 分页排序
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        // 获取返佣订单
        list($total_amount, $list) = $this->getBackOrderData($condition);
        // 总金额
        $total_text = SellGoodsBackOrder::TRANSFER_STATUS_TEXT[$condition['data_status']] ?? '';
        $tips = "<div class='alert alert-info'>{$total_text}金额:<span style='color:red;font-size: 30px;'><b>{$total_amount}</b></span>元</div>";
        // 页面
        $grid = $this->formatGrid($list, $total, $page, $pageSize, $request);

        $tab = new Tab();
        $tab->add('返佣转账', null);
        $tab->addLink('操作记录', '/admin/Peanut/Transfer/Record');
        return $content
            ->header("返佣转账")
            ->body($tab)
            ->row($tips)
            ->breadcrumb(['text' => "返佣转账"])
            ->row($grid);
    }

    // 构造查询条件
    private function getSearchWhere(Request $request)
    {
        $condition = [];
        $pay_date = $request->input('pay_date', []);
        $end_date = $request->input('end_date', []);
//        $info_group = $request->input('info_group', 0);
//        $info = $request->input('info', '');
        $phone = $request->input('phone', '');
        $name = $request->input('name', '');
        $rid = $request->input('rid', '');


//        $request->merge([
//            'name' => '',
//        ]);

        $condition['data_status'] = 1; // 待转账
        $condition['tk_status'] = 3; // 订单已结算

        $month_start = date('Y-m-01 00:00:00', strtotime('-1 month'));
        $month_end = date('Y-m-d H:i:s', strtotime('+1 month', strtotime($month_start)) - 1);


        if (!empty($pay_date['start'])) {
            $condition['tk_paid_time[>=]'] = $pay_date['start'];
        }
        if (!empty($pay_date['end'])) {
            if ($pay_date['end'] > date('Y-m-01 00:00:00', time())) {
                $pay_date['end'] = $month_end;
            }
            $condition['tk_paid_time[<=]'] = $pay_date['end'];
        } else {
            $condition['tk_paid_time[<=]'] = $month_end;
        }

        if (!empty($end_date)) {
            if ($end_date['start']) {
                $condition['tk_earning_time[>=]'] = $end_date['start'];
            }
            if ($end_date['end']) {
                $condition['tk_earning_time[<=]'] = $end_date['end'];
            }
        }


        // 如果有用户的查询条件
        $condition_user = [];
        if (empty($rid)) {
            if (!empty($phone)) {
                $condition_user['account_phone'] = $phone;
            }
            if (!empty($name)) {
                $condition_user['account_name'] = $name;
            }
            if (!empty($condition_user)) {
                $account_info = SellGoodsAccountInfo::select(['uid'], $condition_user);
                if ($account_info) {
                    $condition['uid'] = array_column($account_info, 'uid');
                } else {
                    $condition['uid'] = 0;
                }
            }
        } else {
            $condition['relation_id'] = $rid;
        }

        // 分组
        $condition['GROUP'] = ['uid'];

        return $condition;
    }

    // 返佣订单数据
    private function getBackOrderData($condition)
    {
        $list = SellGoodsBackOrder::select('*', $condition);
        unset($condition['GROUP']);
        unset($condition['ORDER']);
        unset($condition['LIMIT']);
        // 获取筛选条件总金额
        $total_amount = sprintf("%.2f", SellGoodsBackOrder::getWaitAmount($condition));

        $uids = array_column($list, 'uid');
        $user_info = SellGoodsAccountInfo::getAccountInfoByUids('*', $uids);
        $info_uids = array_column($user_info, 'uid');
        $relation_ids = !empty($uids) ? TaoBaoUserAuth::getRelationIdsByUid($uids) : [];
//        $condition['LIMIT'] = [0, 100];
        $limit = 50;
        foreach ($uids as $uid) {
            if (!in_array($uid, $info_uids)) {
                $user_info[] = [
                    'uid' => $uid
                ];
            }
        }
        foreach ($user_info as &$value) {
            $condition['uid'] = $value['uid'];
            // 姓名
            $user = User::getBasicInfo($value['uid']);
            $value['name'] = $user['name'] ?? '';

            // relation_id
            $value['relation_id'] = $relation_ids[$value['uid']] ?? '';

            $value['total_commission_fee'] = sprintf("%.2f", SellGoodsBackOrder::sum('total_commission_fee as sum', $condition));

            $total = SellGoodsBackOrder::count($condition);
            $value['back_total_big'] = 0;
            if ($total > $limit) {
                $value['back_total_big'] = 1;
            }
            $back_list = SellGoodsBackOrder::select('*', $condition + ['LIMIT' => [0, $limit]]);
            $value['back_list_grid'] = $this->formatGridBackList($back_list);
            $back_lists = SellGoodsBackOrder::select(['id'], $condition);
            $value['back_ids'] = implode(',', array_column($back_lists, 'id'));
            $value['data_status'] = $condition['data_status'];
        }
        unset($list);
        return [$total_amount, $user_info];
    }

    // 组装展示表格
    private function formatGrid($list, $total, $page, $pageSize, Request $request)
    {
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize,
            'currentPage' => $page
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $request) {
                $grid->disableCreateButton();
                $grid->disableExport();


                // 批量操作
                $grid->tools(function (Grid\Tools $tools) use ($request) {
                    $tools->batch(function (BatchActions $batch) use ($request) {
                        $batch->disableDelete();
                        /*if ($request->get('status') != 1) {
                            $batch->add("批量待转账", new TagManyStatus(1));
                        }
                        if ($request->get('status') != 2) {
                            $batch->add("批量转账成功", new TagManyStatus(2));
                        }
                        if ($request->get('status') != 3) {
                            $batch->add("批量转账失败", new TagManyStatus(3));
                        }*/

                        if ($request->get('status') != 2) {
                            $batch->add("批量转账成功", new TagManyStatus(2));
                            $batch->add("批量转账失败", new TagManyStatus(3));
                        }
                    });
                });

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function (Grid\Filter $filter) {
//                        $filter->between('pay_date', '支付时间')->date();
//                        $filter->between('end_date', '结束时间')->date();
                        $filter->dropDown('time', [
                            'pay_date' => '支付时间',
                            'end_date' => '结算时间'
                        ])->betweenDatetime();
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
//                        $filter->equal('status', '转账状态')->select(SellGoodsBackOrder::TRANSFER_STATUS_TEXT);
//                        $filter->group('info', '用户信息', function (Grid\Filter\AbstractFilter $group) {
//                            $group->equal('云账户手机号');
//                            $group->equal('云账户姓名');
//                            $group->equal('阿里妈妈RID');
//                        });
                        $filter->dropDown('info', [
                            'phone' => '云账户手机号',
                            'name' => '云账户姓名',
                            'rid' => '阿里妈妈RID'
                        ]);
                    });
                    $filter->expand();
                });

                $grid->column('id', 'ID')->width(50);
                $grid->column('uid', 'Uid')->expand(function () {
                    return $this->back_list_grid;
                })->width(100);
                $grid->column('name', '带货人姓名')->width(150);
                $grid->column('relation_id', 'rid')->width(100);
                $grid->column('total_commission_fee', '待转账金额')->width(100);
                $grid->column('account_name', '云账户姓名')->width(150);
                $grid->column('account_phone', '云账户手机号')->width(100);
                $grid->column('account_identity_number', '云账户身份证')->width(200);
                $grid->column('account_number', '云账户收款账号')->width(200);


//                $grid->setActionClass(Grid\Displayers\DropdownActions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) use ($request) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
//                    $actions->add(new TagSuccessStatus());
//                    $actions->add(new TagFailStatus());
                    $row = $actions->row->toArray();
                    /*$actions->append(new EditBackStatus($row['uid'], $row['back_ids']));
                    if ($row['data_status'] != 1) {
                        $actions->append(new EditBackStatus($row['uid'], $row['back_ids'], 1));
                    }
                    if ($row['data_status'] != 2) {
                        $actions->append(new EditBackStatus($row['uid'], $row['back_ids'], 2));
                    }
                    if ($row['data_status'] != 3) {
                        $actions->append(new EditBackStatus($row['uid'], $row['back_ids'], 3));
                    }*/
                    if ($row['data_status'] != 2) {
                        $actions->append(new EditBackStatus($row['uid'], $row['back_ids']));
                        $actions->append(new EditBackStatus($row['uid'], $row['back_ids'], 2));
                        $actions->append(new EditBackStatus($row['uid'], $row['back_ids'], 3));
                    }
                    if ($row['back_total_big'] == 1) {
                        $params = $request->all();
                        $actions->append(
                            '<a class="btn btn-xs btn-info fa" href="javascript:layer.open({
                                    type: 2,
                                    title: \'查看详情\',
                                    maxmin: true,
                                    area: [\'1200px\', \'600px\'],
                                    content: \'/admin/Peanut/Transfer/Show/' . $row['uid'] . '/ ' . base64_encode(json_encode($params)) . '\'
                                    });"
                             >查看详情</a>'
                        );
                    }
                });
            }
        );
        return $grid;
    }

    // 组装二级表格
    private function formatGridBackList($backList)
    {
        $row = new Row();
        $gridModel = new pGridDataModel($backList, null, [
            'currentPage' => 1
        ]);
        $grid = new Grid($gridModel);
        $grid->disablePagination();
        $grid->disableCreateButton();
        $grid->disableFilter();
        $grid->disableRowSelector();
        $grid->disableColumnSelector();
        $grid->disableTools();
        $grid->disableExport();

        $grid->column('id', 'Id')->width(50);
        $grid->column('item_title', '商品名称')->width(200);
        $grid->column('pay_price', '金额')->width(100);
        $grid->column('total_commission_rate', '返佣比例')->display(function () {
            return $this->total_commission_rate . '%';
        })->width(100);
        $grid->column('total_commission_fee', '返佣金额')->width(100);
        $grid->column('tk_status', '订单状态')->display(function () {
            switch ($this->tk_status) {
                case 3:
                    $text = '订单结算';
                    break;
                case 11:
                    $text = '拍下未付款';
                    break;
                case 12:
                    $text = '订单付款';
                    break;
                case 13:
                    $text = '订单失败';
                    break;
                case 14:
                    $text = '订单成功';
                    break;
                default:
                    $text = '其他';
                    break;
            }
            return $text;
        })->width(100);
        $grid->column('tk_paid_time', '支付时间')->width(150);
        $grid->column('tk_earning_time', '结算时间')->width(150);
        $grid->column('data_status', '转账状态')->display(function () {
            return SellGoodsBackOrder::TRANSFER_STATUS_TEXT[$this->data_status] ?? '';
        })->width(150);

        $grid->disableActions();


        $row->column('12', $grid);
        return $row->render();
    }

    public function show($uid, $params)
    {
        $params = json_decode(base64_decode($params), true);
        $condition = [];
        $pay_date = $params['pay_date'] ?? [];
        $end_date = $params['end_date'] ?? [];

//        if ($status == 1) {
//            $request->merge([
//                'status' => 1,
//            ]);
//        }
        $condition['data_status'] = 1;

        $month_start = date('Y-m-01 00:00:00', strtotime('-1 month'));
        $month_end = date('Y-m-d H:i:s', strtotime('+1 month', strtotime($month_start)) - 1);
        if (!empty($pay_date['start'])) {
            $condition['tk_paid_time[>=]'] = $pay_date['start'];
        }
        if (!empty($pay_date['end'])) {
            if ($pay_date['end'] > date('Y-m-01 00:00:00', time())) {
                $pay_date['end'] = $month_end;
            }
            $condition['tk_paid_time[<=]'] = $pay_date['end'];
        } else {
            $condition['tk_paid_time[<=]'] = $month_end;
        }
        if (!empty($end_date)) {
            if ($end_date['start']) $condition['tk_earning_time[>=]'] = $end_date['start'];
            if ($end_date['end']) $condition['tk_earning_time[<=]'] = $end_date['end'];
        }
        $condition['uid'] = $uid;
        $user_info = SellGoodsAccountInfo::getAccountByUid($uid);
        $user_info['relation_id'] = TaoBaoUserAuth::getRelationIdByUid($uid);
        $user = User::getBasicInfo($uid);
        $user_info['name'] = $user['name'] ?? '';
        $user_info['total_amount'] = sprintf('%.2f', SellGoodsBackOrder::getWaitAmount($condition));
        $data = SellGoodsBackOrder::select('*', $condition);
        $user_info['total'] = count($data);
        return view("Peanut::transfer.show", ['data' => $data, 'user_info' => $user_info]);
    }

    /**
     * @Notes: 转账标记操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author: weiyizheng
     * @Time: 2021/12/30
     */
    public function operate(Request $request)
    {
        $type = $request->input('type');
        $uid = $request->input('uid');
        $back_ids = $request->input('back_ids');
        $remark = $request->input('remark', '');
        try {
            if (empty($type) || empty($uid) || empty($back_ids)) {
                throw new Exception('缺少参数');
            }
            $this->handleBackStatus($uid, $back_ids, $remark, $type);
        } catch (Exception $exception) {
            return response()->json(['code' => 0, 'title' => $exception->getMessage(), 'msg' => '']);
        }
        return response()->json(['code' => 1, 'title' => '操作成功', 'msg' => 'error']);
    }

    /**
     * @Notes: 批量转账标记
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author: weiyizheng
     * @Time: 2022/1/5
     */
    public function operateBatch(Request $request)
    {
        $back_data = $request->input('back_data', []);
        $type = $request->input('type');
        $remark = $request->input('remark', '');
        try {
            if (empty($back_data) || empty($type)) {
                throw new Exception('缺少参数');
            }
            foreach ($back_data as $value) {
                $uid = $value['uid'];
                $back_ids = $value['back_ids'];
                $this->handleBackStatus($uid, $back_ids, $remark, $type);
            }
        } catch (Exception $exception) {
            return response()->json(['code' => 0, 'title' => $exception->getMessage(), 'msg' => '']);
        }
        return response()->json(['code' => 1, 'title' => '操作成功', 'msg' => 'error']);
    }

    private function handleBackStatus($uid, $back_ids, $remark, $type)
    {
        if (empty($uid) || empty($back_ids)) {
            throw new Exception('缺少参数');
        }
        $back_ids_arr = explode(',', $back_ids);
        if (in_array($type, [SellGoodsBackOrder::TRANSFER_SUCCESS, SellGoodsBackOrder::TRANSFER_FAIL])) {
            $account = SellGoodsAccountInfo::get(['account_name', 'account_phone', 'account_identity_number', 'account_number'], ['uid' => $uid]) ?? []; // 获取账户信息
            if (empty($account) && $type == SellGoodsBackOrder::TRANSFER_SUCCESS) {
                throw new Exception('没有账户信息');
            }
            $account['relation_id'] = TaoBaoUserAuth::getRelationIdByUid($uid);
            SellGoodsBackOrder::action(function () use ($remark, $back_ids_arr, $uid, $back_ids, $account, $type) {
                $res = SellGoodsBackOrder::update(['data_status' => $type, 'remark' => $remark], ['id' => $back_ids_arr]);
                if ($res) {
                    $amount = SellGoodsBackOrder::sum('total_commission_fee as sum', ['id' => $back_ids_arr]);
                    $insert = [
                        'uid' => $uid,
                        'relation_id' => $account['relation_id'],
                        'amount' => $amount,
                        'type' => 1,
                        'order_ids' => $back_ids,
                        'admin_id' => Admin::user()->id,
                        'account_info' => json_encode($account),
                        'data_status' => $type,
                        'remark' => $remark
                    ];
                    $id = SellGoodsTransferRecord::create($insert);
                    if (!$id) {
                        throw new Exception('操作失败');
                    }
                    if ($type == SellGoodsBackOrder::TRANSFER_SUCCESS) {
                        $res_acc = SellGoodsAccountInfo::update(['total_income[+]' => $amount], ['uid' => $uid]);
                        if (!$res_acc) {
                            throw new Exception('操作失败');
                        }
                    }
                } else {
                    throw new Exception('操作失败');
                }
            });
        } else {
            throw new Exception('参数有误');
        }
        return true;
    }

    /**
     * @Notes: 操作记录列表
     * @param Content $content
     * @param Request $request
     * @return Content
     * @author: weiyizheng
     * @Time: 2022/1/10
     */
    public function transferRecord(Content $content, Request $request)
    {
        $pageSize = $request->input('per_page', 10);
        $page = $request->input('page', 1);
        $status = $request->input('status');
        $tranfer_time = $request->input('transfer_time', []);
        $phone = $request->input('phone', '');
        $name = $request->input('name', '');
        $rid = $request->input('rid', '');

        $condition = ['deleted_at' => 0];
        if (!empty($status)) {
            $condition['data_status'] = $status;
        } else {
            $condition['data_status'] = [SellGoodsTransferRecord::DATA_STATUS_SUCCESS, SellGoodsTransferRecord::DATA_STATUS_FAIL];
        }
        /*if ($status == 2) {
            $request->merge([
                'status' => 2,
            ]);
        }*/

        if (!empty($tranfer_time)) {
            if ($tranfer_time['start']) $condition['created_at[>=]'] = strtotime($tranfer_time['start']);
            if ($tranfer_time['end']) $condition['created_at[<=]'] = strtotime($tranfer_time['end']);
        }

        // 如果有用户的查询条件
        $condition_user = [];
        if (empty($rid)) {
            if (!empty($phone)) {
                $condition_user['account_phone'] = $phone;
            }
            if (!empty($name)) {
                $condition_user['account_name'] = $name;
            }
            if (!empty($condition_user)) {
                $account_info = SellGoodsAccountInfo::select(['uid'], $condition_user);
                if ($account_info) {
                    $condition['uid'] = array_column($account_info, 'uid');
                } else {
                    $condition['uid'] = 0;
                }
            }
        } else {
            $condition['relation_id'] = $rid;
        }


        $total = SellGoodsTransferRecord::count($condition);

        $list = $this->getTransferList($condition, $page, $pageSize);

        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize,
            'currentPage' => $page
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $request, $pageSize) {
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableBatchActions();
                $grid->paginate($pageSize);
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('status', '转账状态')->select([SellGoodsBackOrder::TRANSFER_SUCCESS => '转账成功', SellGoodsBackOrder::TRANSFER_FAIL => '转账失败']);
                        $filter->dropDown('info', [
                            'phone' => '云账户手机号',
                            'name' => '云账户姓名',
                            'rid' => '阿里妈妈RID'
                        ]);
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->between('transfer_time', '转账时间')->date();
                    });
                    $filter->expand();
                });

                $grid->column('create_time', '转账时间')->width(150);
                $grid->column('id', 'ID')->width(50);
                $grid->column('uid', 'Uid')->expand(function () {
                    return $this->back_list_grid;
                })->width(100);
                $grid->column('name', '带货人姓名')->width(150);
                $grid->column('relation_id', 'rid')->width(100);
                $grid->column('amount', '转账金额')->width(100);
                $grid->column('account_name', '云账户姓名')->width(150);
                $grid->column('account_phone', '云账户手机号')->width(100);
                $grid->column('account_identity_number', '云账户身份证')->width(200);
                $grid->column('account_number', '云账户收款账号')->width(200);
                $grid->column('data_status', '转账状态')->display(function () {
                    $color = '';
                    if ($this->data_status == 2) $color = 'green';
                    if ($this->data_status == 3) $color = 'red';
                    $text = SellGoodsBackOrder::TRANSFER_STATUS_TEXT[$this->data_status];
                    return "<font style='color: {$color}'>{$text}</font>";
                })->width(150);


                $grid->setActionClass(Grid\Displayers\DropdownActions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
//                    $row = $actions->row->toArray();
                    $actions->add(new UndoTransferRecord());
                });
            }
        );

        $tab = new Tab();
        $tab->addLink('返佣转账', '/admin/Peanut/Transfer');
        $tab->add('操作记录', null, true);
        return $content
            ->header("操作记录")
            ->body($tab)
            ->breadcrumb(['text' => "操作记录"])
            ->row($grid);
    }

    private function getTransferList($condition, $page, $pageSize)
    {
        $list = SellGoodsTransferRecord::getListByPage($page, $pageSize, $condition);
        if (!$list) return [];
//        $uids = array_unique(array_column($list, 'uid'));
        foreach ($list as &$value) {
            // 姓名
            $user = User::getBasicInfo($value['uid']);
            $value['name'] = $user['name'] ?? '';

            // 账户信息
            $account_info = json_decode($value['account_info'], true);
            $value['relation_id'] = $account_info['relation_id'] ?? '';
            $value['account_name'] = $account_info['account_name'] ?? '';
            $value['account_phone'] = $account_info['account_phone'] ?? '';
            $value['account_identity_number'] = $account_info['account_identity_number'] ?? '';
            $value['account_number'] = $account_info['account_number'] ?? '';
            $value['create_time'] = date('Y-m-d H:i:s', $value['created_at']);

            // 订单
            $order_ids = explode(',', $value['order_ids']);
            $order_list = SellGoodsBackOrder::select('*', ['id' => $order_ids]);
            $value['back_list_grid'] = $this->formatGridBackList($order_list);
        }
        return $list;
    }
}